package com.rc.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Trip;
import com.rc.activity.dao.tbl_TripDao;
import com.rc.activity.provider.Contract;
import com.rc.db.DatabaseSupport;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class TripEdit extends BaseActivity implements OnClickListener {

	/**
	 * call Itent Trip Edit
	 */

	public static void callIntent(Context ct, tbl_Trip objTrip) {
		Intent it = new Intent(ct, TripEdit.class);
		Bundle b = new Bundle();
		b.putSerializable("OBJECT_TRIP", objTrip);
		it.putExtras(b);
		ct.startActivity(it);
	}

	private LinearLayout llSave, llCancel, llReset;
	private TextView txtEndDate, txtStartDate, txtTripName, txtLeg, txtFrom,
			txtTo, txtTripReference, txtMemo;
	private tbl_Trip objTrip;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.trip_edit);
		((TextView) findViewById(R.id.lbTitle))
				.setText(getString(R.string.edit_trip));

		// register
		llSave = (LinearLayout) findViewById(R.id.llSave);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		llReset = (LinearLayout) findViewById(R.id.llReset);
		txtEndDate = (TextView) findViewById(R.id.txtEndDate);
		txtStartDate = (TextView) findViewById(R.id.txtStartDate);
		txtTripName = (TextView) findViewById(R.id.txtTripName);
		txtLeg = (TextView) findViewById(R.id.txtLeg);
		txtFrom = (TextView) findViewById(R.id.txtFrom);
		txtTo = (TextView) findViewById(R.id.txtTo);
		txtTripReference = (TextView) findViewById(R.id.txtTripReference);
		txtMemo = (TextView) findViewById(R.id.txtMemo);

		// funtion
		txtTripReference.setEnabled(false);
		llSave.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		llReset.setOnClickListener(this);
		txtEndDate.setOnClickListener(this);
		txtStartDate.setOnClickListener(this);

		if (getIntent() != null) {
			objTrip = new tbl_Trip();
			if (getIntent() != null) {
				objTrip = (tbl_Trip) getIntent().getSerializableExtra(
						"OBJECT_TRIP");
				addDataUI(objTrip);
			}
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.llReset:
			addDataUI(objTrip);
			break;
		case R.id.llSave:
			if (updateData() != -1) {
				finish();
			}
			break;
		case R.id.llCancel:
			finish();
			break;
		case R.id.txtEndDate:
			showDatePickerDialog(true);
			break;
		case R.id.txtStartDate:
			showDatePickerDialog(false);
			break;
		default:
			break;
		}
	}

	/**
	 * update database SQLite
	 */

	private int updateData() {
		if (vaildateUI()) {
			return this.getContentResolver().update(
					Contract.CONTENT_URI_TRIP,
					getDataFromUI().getContentValues(),
					tbl_TripDao.Properties.TripID.columnName + " = '"
							+ getDataFromUI().getTripID() + "'", null);
		}
		return 0;

	}

	/**
	 * validate data from UI
	 */
	private boolean vaildateUI() {
		if (!Util.validateText(txtTripName)) {
			Util.setError((EditText) txtTripName,
					getString(R.string.input_trip_name));
		} else if (!Util.validateText(txtFrom)) {
			Util.setError((EditText) txtFrom, getString(R.string.input_from));
		} else if (!Util.validateText(txtTo)) {
			Util.setError((EditText) txtTo, getString(R.string.input_to));
		} else {
			return true;
		}
		return false;
	}

	/**
	 * get data from UI insert object
	 */
	@SuppressLint("SimpleDateFormat")
	private tbl_Trip getDataFromUI() {
		objTrip.setName(txtTripName.getText().toString());
		objTrip.setMemo(txtMemo.getText().toString());
		int leg = "".endsWith(txtLeg.getText().toString()) ? 0 : 1;
		objTrip.setTripLeg(leg + "");
		objTrip.setDeparture(txtFrom.getText().toString());
		objTrip.setArrival(txtTo.getText().toString());
		objTrip.setMemo(txtMemo.getText().toString());
		objTrip.setStartDate(txtStartDate.getText().toString());
		objTrip.setEndDate(txtEndDate.getText().toString());
		int startInt = Util.parseDateForInt(txtStartDate.getText().toString());
		objTrip.setStartDateInt(startInt);
		objTrip.setFilterDate(startInt);
		objTrip.setIsUpdate("1");
		int endInt = Util.parseDateForInt(txtEndDate.getText().toString());
		Date date = Calendar.getInstance().getTime();
		SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");

		int datenowInt = Util.parseDateForInt(dateformat.format(date));
		String tripType = "";
		if (endInt < datenowInt && startInt < datenowInt) {
			tripType = getString(R.string.past_trips);
		} else if (endInt > datenowInt && startInt > datenowInt) {
			tripType = getString(R.string.upcoming_trips);
		} else {
			tripType = getString(R.string.current_trips);
		}
		objTrip.setType(tripType);
		objTrip.setEndDateInt(endInt);
		objTrip.setReference(txtTripReference.getText().toString());
		return objTrip;
	}

	/**
	 * show hidden content if the trip belong to report which is draft report
	 */

	private void showAndHiddenContent(boolean isShow) {
		txtEndDate.setEnabled(isShow);
		txtFrom.setEnabled(isShow);
		txtLeg.setEnabled(isShow);
		txtMemo.setEnabled(isShow);
		txtStartDate.setEnabled(isShow);
		txtTo.setEnabled(isShow);
		txtTripName.setEnabled(isShow);
		txtTripReference.setEnabled(isShow);
		if (isShow) {
			llSave.setVisibility(View.VISIBLE);
			llReset.setVisibility(View.VISIBLE);
		} else {
			llReset.setVisibility(View.GONE);
			llSave.setVisibility(View.GONE);
		}

	}

	/**
	 * add data for UI
	 */
	private void addDataUI(tbl_Trip objTrip) {
		if (objTrip == null) {
			return;
		} else {
			txtEndDate.setText(objTrip.getEndDate());
			txtStartDate.setText(objTrip.getStartDate());
			txtTripName.setText(objTrip.getName());
			txtLeg.setText(objTrip.getTripLeg());
			txtFrom.setText(objTrip.getDeparture());
			txtTo.setText(objTrip.getArrival());
			txtTripReference.setText(objTrip.getReference());
			txtMemo.setText(objTrip.getMemo());
			showAndHiddenContent(DatabaseSupport.check_editTrip(
					objTrip.getTripID(), TripEdit.this));
		}
	}

	/**
	 * isEndDate = true - > show End isEndDate = false - > show start
	 */
	public void showDatePickerDialog(final boolean isEndDate) {
		int date = 0, month = 0, year = 0;

		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// Date
				String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth
						+ "";
				String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1)
						: (monthOfYear + 1) + "";
				String textDate = day + "-" + month + "-" + year;
				if (isEndDate) {

					int startInt = Util.parseDateForInt(txtStartDate.getText()
							.toString());
					int endInt = Util.parseDateForInt(textDate);
					if (endInt >= startInt) {
						txtEndDate.setText(textDate);
					}
				} else {
					int startInt = Util.parseDateForInt(textDate);
					int endInt = Util.parseDateForInt(txtEndDate.getText()
							.toString());
					if (endInt >= startInt) {
						if (checkStartDate(textDate)) {
							txtStartDate.setText(textDate);
							txtTripReference.setText(validateReference("R"
									+ Util.parseDateForInt(textDate)));
						}
					}

				}

			}
		};
		String s = "";
		if (isEndDate) {
			s = txtEndDate.getText() + "";
		} else {
			s = txtStartDate.getText() + "";
		}
		if ("".equals(s)) {
			return;
		}
		s = s.replace("/", "-");
		if (s.indexOf("-") >= 0) {
			String strArrtmp[] = s.split("-");
			date = Integer.parseInt(strArrtmp[0]);
			month = Integer.parseInt(strArrtmp[1]) - 1;
			year = Integer.parseInt(strArrtmp[2]);

			DatePickerDialog pic = new DatePickerDialog(TripEdit.this,
					callback, year, month, date);
			if (isEndDate) {
				pic.setTitle(getString(R.string.choose_end_date));
			} else {
				pic.setTitle(getString(R.string.choose_start_date));
			}
			pic.show();
		}

	}

	/**
	 * Kiểm tra biến reference trong database nếu đã tồn tại thì + 1 theo mã
	 * hexadecimal
	 */
	private String validateReference(String reference) {

		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_TRIP,
				null,
				tbl_TripDao.Properties.Reference.columnName + " like '"
						+ reference + "%' ", null, null);
		ArrayList<tbl_Trip> arrTrip = new ArrayList<tbl_Trip>();
		arrTrip = tbl_Trip.getObjectbyCursor(cursor);
		if (arrTrip.size() > 0) {
			reference = arrTrip.get((arrTrip.size() - 1)).getReference();
			String key = reference.substring(reference.length() - 1,
					reference.length());
			try {
				Integer.parseInt(key);
				int i = 11;
				reference = (reference + Integer.toHexString(i)).toUpperCase();
			} catch (NumberFormatException e) {
				int decimal = Integer.parseInt(key, 16);
				decimal = decimal + 1;
				reference = reference.substring(0, (reference.length() - 1));
				reference = (reference + Integer.toHexString(decimal))
						.toUpperCase();

			}
		}
		return reference;
	}

	/**
	 * check sqlite startdate
	 */

	private boolean checkStartDate(String startDate) {
		int startInt = Util.parseDateForInt(startDate);
		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_TRIP,
				null,
				startInt + " <= "
						+ tbl_TripDao.Properties.EndDateInt.columnName
						+ " and " + startInt + " > "
						+ tbl_TripDao.Properties.StartDate.columnName, null,
				null);
		ArrayList<tbl_Trip> arrTrip = new ArrayList<tbl_Trip>();
		arrTrip = tbl_Trip.getObjectbyCursor(cursor);
		if (arrTrip.size() > 0) {
			return false;
		}

		return true;
	}
}
